import { defineStore } from 'pinia';
import { orderBy, unionWith, get } from 'lodash';
import { handleCommonResult } from '../utils/resolver';
import { assign, getReplacedData, mergeValidData, parseJson, parseStr } from '../utils/tools';

export const appStore = defineStore('appStore', {
  state: () => ({
    data: {},
  }),
  getters: {
    getReplacedTempData(state) {
      return (fields, option) => {
        if (typeof fields === 'object') {
          return getReplacedData(state.data, fields);
        }
        if (typeof fields === 'string') {
          const { fieldsMap, parseType, defaultJson } = assign(option, {
            fieldsMap: null,
            parseType: 'json',
            defaultJson: {},
          });
          const parse = { json: parseJson, string: parseStr };
          const tempData = parse[parseType](get(state.data, fields), defaultJson);
          return typeof fieldsMap === 'object' && fieldsMap ? getReplacedData(tempData, fieldsMap) : tempData;
        }
      };
    },
    getMergedData(state) {
      return (dataSource, fields, option) => {
        const tempData = this.getReplacedTempData(fields, option);
        if (!tempData) {
          return dataSource;
        }
        return mergeValidData(dataSource, [tempData]);
      };
    },
    getMergedList(state) {
      return (dataSource, fields, option) => {
        let { format, keyField, valueField, uniqueKey, orderKey, order } = assign(option, {
          format: null,
          keyField: null,
          valueField: null,
          uniqueKey: 'name',
          orderKey: 'value',
          order: 'desc',
        });
        let tempList = this.getReplacedTempData(fields, assign(option, { defaultJson: [] }));
        if (typeof format === 'function') {
          tempList = format(tempList);
        }
        if (!tempList || !tempList.length) {
          return dataSource;
        }
        if (keyField && valueField) {
          const data = tempList.reduce((res, item) => {
            return Object.assign(res, { [item[keyField]]: item[valueField] });
          }, {});
          return dataSource.map((item) => {
            return mergeValidData(item, [{ [valueField]: data[item[keyField]] }]);
          });
        } else {
          const list = unionWith(tempList, dataSource, (m, n) => {
            return m[uniqueKey] === n[uniqueKey];
          });
          return order === null || order === false ? list : orderBy(list, orderKey, order);
        }
      };
    },
  },
  actions: {
    async getTempShowListAsync() {
      const userInfo = userInfoStore();
      const params = { area_code: userInfo.area_code };
      this.data = handleCommonResult(
        await getVueGlobalProperty('$axios').get('/xw-microservice/xw-api/v3/tempShow/list/open', {
          params,
        })
      );
    },
  },
});
